import axios from 'axios'
import { showAlert, loading, hiddenLoading } from '@/utils/ComponentRegister'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000, //超时时间
})

let loadingApp: any
//配置请求拦截器,在请求之前的数据处理,比如在请求头添加token,所有的请求都会经过拦截器
instance.interceptors.request.use(
  //config:该参数表示当前请求的配置对象
  (config) => {
    //在请求头统一添加token
    //或者请求之前显示lodding图标(这里只演示这个)
    loadingApp = loading('加载中...')
    return config
  },
  (err) => {
    return Promise.reject(err)
  },
)

//配置响应拦截器
instance.interceptors.response.use(
  (response) => {
    const httpStatus = response.status
    if (httpStatus !== 200) {
      console.log('服务器错误')
    }
    let apiStatus = response.data.code
    hiddenLoading(loadingApp)
    switch (apiStatus) {
      case 200:
        return response.data.data
      case 11011:
        showAlert('登录已过期，请重新登录', 'error')
        localStorage.removeItem('yzxToken')
        return Promise.reject(response.data)
      case 11012:
        showAlert('token已失效，请重新登录', 'error')
        localStorage.removeItem('yzxToken')
        return Promise.reject(response.data)
      case 11016:
        showAlert('登录已过期，请重新登录', 'error')
        localStorage.removeItem('yzxToken')
        return Promise.reject(response.data)
      default:
        errorHandler(response.data)
        return Promise.reject(response.data)
    }
  },
  (err) => {
    hiddenLoading(loadingApp)
    return Promise.reject(err)
  },
)

const errorHandler = (data: any) => {
  showAlert(data.msg, 'error')
}

//封装请求的api
const api = (method = 'GET', url: string, data = {}) => {
  return instance({
    method,
    url,
    params: method === 'GET' ? data : {},
    data: method === 'POST' || method === 'PUT' ? data : {},
  })
}

export const get = (url: string, data: any) => api('GET', url, data)
export const post = (url: string, data: any) => api('POST', url, data)
export const put = (url: string, data: any) => api('PUT', url, data)
export const remove = (url: string, data: any) => api('DELETE', url, data)
